package com.ovo.rxandroiddemo.utils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.util.DisplayMetrics;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;

import androidx.annotation.RequiresApi;

import com.ovo.rxandroiddemo.app.BaseApplication;

/***
 * 支付
 */
public class WebViewUtils {
    private final String TAG = this.getClass().getSimpleName();
    private static WebViewUtils webViewUtils = null;

    private WebView webView;

    private PopupWindow popupWindow;

    public static WebViewUtils getInstance(){
        if (webViewUtils == null){
            synchronized (WebViewUtils.class){
                if (webViewUtils == null){
                    webViewUtils = new WebViewUtils();
                }
            }
        }
        return webViewUtils;
    }

    /**
     * 打开webview
     */
    public void openWebView(WebView webView, String url){
        this.webView = webView;
        initWebViewSetting();

        webView.loadUrl(url);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebViewSetting() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        // 设置自适应屏幕，两者合用
        // 将图片调整到适合WebView的大小
        settings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        settings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            // https 和 http 混合模式
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        DisplayMetrics dm = new DisplayMetrics();
        BaseApplication.activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (dm.densityDpi > 240 ) {
            settings.setDefaultFontSize(40); //可以取1-72之间的任意值，默认16
        }

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 忽略SSL证书错误，继续加载页面
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                try {
                    LogUtils.log(TAG, "shouldOverrideUrlLoading==>" + request.getUrl());
                    if (request.getUrl().toString().startsWith("scheme")){
                        Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
                        BaseApplication.activity.startActivity(intent);
                        return true;
                    }
                }catch (Exception e){
                    return false;
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });

//        webView.setWebChromeClient(new WebChromeClient(){
//            @Override
//            public void onReceivedTitle(WebView view, String title) {
//                super.onReceivedTitle(view, title);
//                LogUtils.log(TAG, title);
//                if (title.indexOf("https://") != -1){
//                    payByUrl(webView, title);
//                }
//            }
//        });
    }

    /**
     * 返回键
     * @return
     */
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        }
    }

    public void onDestroy() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        }
        if (popupWindow != null && popupWindow.isShowing()){
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

}
